<script lang="ts" setup>
import { type InputHTMLAttributes, type PropType, toRefs, computed, ref } from 'vue';
import { twMerge, useTwMergeRoot } from '@storefront-ui/vue';

const props = defineProps({
  modelValue: {
    type: [String, Array, Boolean] as PropType<InputHTMLAttributes['checked']>,
    default: false,
  },
  value: {
    type: String,
    default: '',
  },
  invalid: {
    type: Boolean,
    default: false,
  },
});

defineOptions({
  inheritAttrs: false,
});
const { attrsWithoutClass } = useTwMergeRoot();

const { modelValue } = toRefs(props);
const emit = defineEmits<{
  (event: 'update:modelValue', param: InputHTMLAttributes['checked']): void;
}>();

const switchRef = ref();
const proxyChecked = computed({
  get: () => modelValue?.value,
  set: (value) => emit('update:modelValue', value),
});
</script>

<!-- switchRef?.checked is used instead of model because model is value collection of multiple inputs, we need to have this one input check value -->
<template>
  <input
    ref="switchRef"
    v-model="proxyChecked"
    :class="
      twMerge(
        `appearance-none h-5 min-w-[36px] bg-transparent border-2 border-gray-500 rounded-full relative ease-in-out duration-300 hover:border-primary-800 hover:checked:before:bg-white checked:before:left-1/2 checked:before:ml-0 checked:before:mr-0.5 disabled:before:bg-gray-500/50 hover:before:bg-primary-800 active:border-primary-800 active:before:bg-primary-800 checked:bg-none checked:bg-primary-700 checked:border-primary-700 checked:before:bg-white hover:checked:bg-primary-800 hover:checked:border-primary-800 disabled:border-gray-500/50 checked:disabled:before:bg-white checked:disabled:bg-gray-500/50 checked:disabled:border-0 before:transition-all  before:w-3.5 before:h-3.5 before:bg-gray-500 before:absolute before:top-0 before:bottom-0 before:my-auto before:rounded-full before:left-0 before:ml-0.5 before:ease-in-out before:duration-300 cursor-pointer disabled:cursor-not-allowed focus-visible:outline focus-visible:outline-offset`,
        {
          'border-negative-700 hover:border-negative-800 active:border-negative-900 before:bg-negative-900': invalid,
        },
        $attrs.class,
      )
    "
    :value="value"
    type="checkbox"
    role="switch"
    data-testid="switch"
    :aria-checked="switchRef?.checked"
    v-bind="attrsWithoutClass"
  />
</template>
